<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Croptype;
use app\admin\model\Varieties;

use think\Db;
use think\Exception;
use think\Request;

class Crop extends Base
{
    public function _initialize() {
        parent::_initialize();

        $typeId = $this->request->param('typeId');
        $defaultWhere = [];
        $defaultWhere['typeId'] = $typeId;
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'name' => [
                'label'     => '名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        $this->assign('typeId', $typeId);
        $typeName = Croptype::where('id', $typeId)->value('name');
        $this->assign('typeName', $typeName);
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere) {
                $where = array_merge($where, $this->defaultWhere);
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as $item) {
                // 品种数
                $countVarieties = Varieties::where('cropId', $item->id)->count();
                $item->countVarieties = $countVarieties;
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        // 品类
        $typeList = Croptype::order('sorting ASC')->select();
        $this->assign('typeList', $typeList);

        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {
        $params = $request->param();
        if(is_array($params['phenological'])){
            $request->post(['phenological' => implode(',', (Array)$params['phenological'])]);
        }
        if(is_array($params['farmingProject'])){
            $request->post(['farmingProject' => implode(',', (Array)$params['farmingProject'])]);
        }
        $redirect = url('admin/crop/index', ['typeId' => $request->param('typeId')]);

        return parent::addPost($request, $redirect);
    }

    public function edit(Request $request) {

        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){
        $params = $request->param();
        if(is_array($params['phenological'])){
            $request->post(['phenological' => implode(',', (Array)$params['phenological'])]);
        }
        if(is_array($params['farmingProject'])){
            $request->post(['farmingProject' => implode(',', (Array)$params['farmingProject'])]);
        }
        $redirect = url('admin/crop/index', ['typeId' => $request->param('typeId')]);

        return parent::editPost($request, $redirect);
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            $varieties = Varieties::where(['cropId' => $id])->select();
            if($varieties) {
                return $this->error('该农作物有品种，请先去删除品种！');
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 将肥料移至另一品类
     */
    public function move() {
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            $ids = (Array)$param['ids'];
            foreach ($ids as $id) {
                $result = $model->where('id', $id)->update(['typeId' => $param['typeId']]);
            }

            if($result !== false) {
                return $this->success('移动成功！');
            } else {
                return $this->error('移动失败！');
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

}
